package cn.lichenes.controller;

import cn.lichenes.entity.User;
import cn.lichenes.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class LoginController {

    @Autowired
    private LoginService loginService;

    @GetMapping("/login-admin")
    public String loginAdmin(){
        return "login-admin";
    }

    @PostMapping("/doLoginAdmin")
    @ResponseBody
    public String doLoginAdmin(String account, String password, HttpSession session){
        System.out.println(account+","+password);
        User admin = loginService.checkAdmin(account,password);
        if (admin != null){
            session.setAttribute("admin",admin);
            return "true";
        }
        return "false";
    }

    @GetMapping("/logout-admin")
    public String logoutAdmin(HttpSession session){
        session.setAttribute("admin",null);
        return "redirect:/login-admin";
    }

    @GetMapping("/lock_screen")
    public String lockScreen(){
        return "lock_screen";
    }

    @GetMapping("/login")
    public String loginUser(){
        return "login";
    }

    @PostMapping("/phoneLoginUser")
    @ResponseBody
    public boolean phoneLoginUser(String phone,HttpSession session){
        User user = loginService.checkPhone(phone);
        session.setAttribute("user",user);
        if (user != null){
            return true;
        }
        return false;
    }

    @PostMapping("/doLoginUser")
    @ResponseBody
    public boolean doLoginUser(String name,String pwd,HttpSession session){
        String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        Pattern p = Pattern.compile(check);
        Matcher m = p.matcher(name);
        User user = null;
        if (m.matches()) {
            user = loginService.checkEmail(name, pwd);
        }else {
            user = loginService.checkUser(name, pwd);
        }
        if (user != null){
            session.setAttribute("user",user);
            return true;
        }
        return false;
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.setAttribute("user",null);
        return "redirect:/shopIndex";
    }
}
